//
//  ViewController.m
//  区域截图实现
//
//  Created by hyl on 16/6/27.
//  Copyright © 2016年 hyl. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (nonatomic,assign) CGPoint startP;

@property (nonatomic,weak) UIView *clipView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setPan];
}

-(UIView *) clipView{
    if (_clipView==nil) {
        UIView *view=[[UIView alloc]init];
        view.backgroundColor=[UIColor blackColor];
        view.alpha=0.4;
        _clipView=view;
        [self.view addSubview:_clipView];
    }
    return _clipView;
}

#pragma mark - setPan
//注意一点，uiimageview默认是不响应事件的,找错误花了不少时间
-(void) setPan{
    UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self.imageView addGestureRecognizer:pan];
}
-(void) pan:(UIPanGestureRecognizer *) pan{
    CGPoint endP=CGPointZero;
    CGRect clipRect;
    if (pan.state==UIGestureRecognizerStateBegan) {
        _startP=[pan locationInView:_imageView];
        
    }else if (pan.state==UIGestureRecognizerStateChanged){
        endP=[pan locationInView:_imageView];
        clipRect=CGRectMake(_startP.x, _startP.y, endP.x-_startP.x, endP.y-_startP.y);
        //使用懒加载
//        UIView *view=[[UIView alloc]init];
//        view.backgroundColor=[UIColor blackColor];
//        view.alpha=0.4;
//        _clipView=view;
//        _clipView.frame=clipRect;//不能调用get方法
          self.clipView.frame=clipRect;
//        [self.view addSubview:_clipView];
        
        
    }else if (pan.state==UIGestureRecognizerStateEnded){
        
        //获得图片上下文
        UIGraphicsBeginImageContextWithOptions(_imageView.bounds.size, NO, 0);
//        //获得图片上下文   //不能在截切区域设置之前获取上下文
//        CGContextRef context=UIGraphicsGetCurrentContext();
//        //将整个屏幕添加到上下文上
//        [self.view.layer renderInContext:context];
        //添加截切
//        UIBezierPath *path=[UIBezierPath bezierPathWithRect:clipRect];//用这个只会得到空白
        NSLog(@"%@",NSStringFromCGRect(clipRect));
        NSLog(@"%@",NSStringFromCGRect(_clipView.frame));
        UIBezierPath *path=[UIBezierPath bezierPathWithRect:_clipView.frame];
        [path addClip];
        //获得图片上下文
        CGContextRef context=UIGraphicsGetCurrentContext();
//        //将整个屏幕添加到上下文上
       [self.view.layer renderInContext:context];
        //从上下文中获得图片
        UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
        //关闭图片上下文
        UIGraphicsEndImageContext();
        //写到指定的文件夹中
        NSData *data=UIImageJPEGRepresentation(image, 1);
        [data writeToFile:@"/Users/hyl/Desktop/素材/view.jpg" atomically:YES];
        //取消鼠标拉得矩形
        [_clipView removeFromSuperview];
        _clipView=nil;
    }
}

@end
